#include <rtthread.h>
#include <rtdevice.h>
#include "touch.h"
#include "board.h"
#include "drv_touch.h"
#include "drv_lcd.h"
#include "touch_port.h"
#include "lcd_port.h"

#if TOUCH_USE

#if TOUCH_USE_NS2009
#include "drv_touch_ns2009.h"
#endif
#if TOUCH_USE_XPT2046
#include "touch_xpt2046.h"
#endif
#if TOUCH_USE_GT911
#include "touch_gt911.h"
#endif
#if TOUCH_USE_FT5x06
#include "drv_touch_ft5x06.h"
#endif

#define TP_INT_PIN GPIO_PORT_E,GPIO_PIN_3
#define TP_RST_PIN GPIO_PORT_E,GPIO_PIN_4

rt_device_t touch_dev;
struct rt_touch_data touch_read_data;

int board_touch_read_status(struct touch_message *msg)
{
	if(gpio_get_value(TP_INT_PIN)==0)
	{
		rt_device_read(touch_dev, 0, &touch_read_data, 1);
		msg->event = touch_read_data.event;
		msg->track_id = touch_read_data.track_id;
		msg->timestamp = touch_read_data.timestamp;
		msg->x_coordinate = LCD_WIDTH - touch_read_data.y_coordinate;
		msg->y_coordinate = touch_read_data.x_coordinate;
		//rt_kprintf("X:%d Y:%d  %d\n",msg->x,msg->y,msg->event);
	}else
	{
		msg->event = TOUCH_EVENT_NONE;
	}
	return 0;
}


int touchstate(uint8_t argc, char **argv)
{
	struct touch_message msg;
	
	board_touch_read_status(&msg);
	
	rt_kprintf("[%d]touch [%d]event:%d x:%d y:%d \n",msg.timestamp, msg.track_id, msg.event, msg.x_coordinate, msg.y_coordinate);
	return 0;
}
MSH_CMD_EXPORT(touchstate, touchstate);

int touchinfo(uint8_t argc, char **argv)
{
    struct rt_touch_info info;
    rt_device_control(touch_dev, RT_TOUCH_CTRL_GET_INFO, &info);
    rt_kprintf("type       :%d", info.type);
    rt_kprintf("vendor     :%d", info.vendor);
    rt_kprintf("point_num  :%d", info.point_num);
    rt_kprintf("range_x    :%d", info.range_x);
    rt_kprintf("range_y    :%d", info.range_y);
	return 0;
}
MSH_CMD_EXPORT(touchinfo, touchinfo);

static int _touch_init = 0;

int drv_touch_init(void)
{
    if(_touch_init == 1)
        return 0;
	
	_touch_init = 1;
	
	rt_kprintf("%s\n",__FUNCTION__);
	gpio_direction_input(TP_INT_PIN);

	#if TOUCH_USE_XPT2046
		touch_xpt2046_init();
	#endif
	#if TOUCH_USE_NS2009
		touch_ns2009_init();
	#endif
	#if TOUCH_USE_GT911
		touch_gt911_init();
	#endif
	#if TOUCH_USE_FT5x06
		struct rt_touch_config cfg;
		cfg.dev_name = "i2c0";
		rt_hw_ft5x06_init("touch", &cfg);
	#endif
    touch_dev = rt_device_find("touch");
    RT_ASSERT(touch_dev != RT_NULL);

    rt_device_open(touch_dev, RT_DEVICE_FLAG_RDONLY);

    struct rt_touch_info info;
    rt_device_control(touch_dev, RT_TOUCH_CTRL_GET_INFO, &info);
    rt_kprintf("touch type       :%d\n", info.type);
    rt_kprintf("touch vendor     :%d\n", info.vendor);
    rt_kprintf("touch point_num  :%d\n", info.point_num);
    rt_kprintf("touch range_x    :%d\n", info.range_x);
    rt_kprintf("touch range_y    :%d\n", info.range_y);
	return 0;
}
//INIT_DEVICE_EXPORT(drv_touch_hw_init);

#endif
